package examexercise;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-08-07
 * Time: 23:14
 */

/**
 * 按之字型顺序打印二叉树
 */
public class ExamExercise2 {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

    }

    public ArrayList<ArrayList<Integer>> Print(TreeNode root) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        TreeNode cur = root;
        Queue<TreeNode> queue = new LinkedList<>();

        //先把根节点放入队列
        queue.offer(cur);

        //定义一个flag,为之后逆置层序遍历做准备
        boolean flag = true;

        //层序遍历
        while (!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> tmp = new ArrayList<>();//第二层开辟

            while (size != 0) {
               cur =  queue.poll();
               tmp.add(cur.val);

                if (cur.left != null) {
                    queue.offer(cur.left);
                }

                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }

            //把第一层放好，第二层逆置
            if (flag /*== true*/) {
                //为下一层逆置做准备
                flag = false;
            }else {

                //逆置
                Collections.reverse(tmp);

                //逆置之后置为true,形成“之”字形
                flag = true;

            }
            //放到二维数组中
            list.add(tmp);
        }

        return list;
    }
}
